//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package com.tl.satoken.controller;

import com.tl.satoken.common.Result;
import com.tl.satoken.domain.entity.MBTISquare;
import com.tl.satoken.domain.entity.Player;
import com.tl.satoken.domain.entity.RoomInfo;
import com.tl.satoken.domain.entity.RoomJoinResult;
import com.tl.satoken.service.RoomService;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping({"/api/game"})
public class GameController {
    private static final Logger log = LoggerFactory.getLogger(GameController.class);
    @Autowired
    private RoomService roomService;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    public GameController() {
    }

    @PostMapping({"/join"})
    public Result<Map<String, Object>> joinGame(@RequestBody Player player) {
        log.info("玩家 {} 通过HTTP请求加入游戏", player.getUsername());
        player.setId(player.getUsername());
        RoomJoinResult result = this.roomService.joinRoom(player);
        if (result.isSuccess()) {
            Map<String, Object> response = Map.of("success", true, "message", result.getMessage(), "roomId", result.getRoomId(), "roomInfo", this.roomService.getRoomInfo(result.getRoomId()));
            return Result.success(response);
        } else {
            Map<String, Object> response = Map.of("success", false, "message", result.getMessage());
            return Result.success(response);
        }
    }

    @GetMapping({"/rooms"})
    public Result<Map<String, Object>> getAllRooms() {
        try {
            List<RoomInfo> rooms = this.roomService.getAllRooms();
            List<Map<String, Object>> roomsWithPlayers = rooms.stream().map((room) -> Map.of("roomInfo", room, "players", this.roomService.getPlayersInRoom(room.getRoomId()))).toList();
            Map<String, Object> response = Map.of("rooms", roomsWithPlayers, "totalRooms", rooms.size(), "totalPlayers", rooms.stream().mapToInt(RoomInfo::getCurrentPlayers).sum(), "activeRooms", rooms.stream().filter((room) -> room.getCurrentPlayers() > 0).count());
            return Result.success(response);
        } catch (Exception e) {
            log.error("获取房间信息时出现异常: {}", e.getMessage(), e);
            return Result.success(Map.of("message", "获取房间信息失败: " + e.getMessage()));
        }
    }

    @GetMapping({"/room/{roomId}"})
    public Result<Map<String, Object>> getRoomInfo(@PathVariable String roomId) {
        RoomInfo roomInfo = this.roomService.getRoomInfo(roomId);
        if (roomInfo != null) {
            Map<String, Object> response = Map.of("roomInfo", roomInfo, "players", this.roomService.getPlayersInRoom(roomId));
            return Result.success(response);
        } else {
            return Result.success(Map.of("message", "房间不存在"));
        }
    }

    @PostMapping({"/cleanup"})
    public Result<Map<String, Object>> cleanupRedis() {
        try {
            Set<String> keys = this.redisTemplate.keys("game:*");
            if (keys != null && !keys.isEmpty()) {
                this.redisTemplate.delete(keys);
                log.info("手动清理了 {} 个游戏数据", keys.size());
                return Result.success(Map.of("message", "清理成功", "count", keys.size()));
            } else {
                return Result.success(Map.of("message", "没有需要清理的数据"));
            }
        } catch (Exception e) {
            log.error("清理Redis数据时出现异常: {}", e.getMessage(), e);
            return Result.success(Map.of("message", "清理失败: " + e.getMessage()));
        }
    }

    @GetMapping({"/connections"})
    public Result<Map<String, Object>> getConnections() {
        Map<String, Object> stats = new HashMap();
        stats.put("activeConnections", this.roomService.getActiveConnections());
        stats.put("totalRooms", this.roomService.getAllRooms().size());
        stats.put("totalPlayers", this.roomService.getTotalPlayers());
        return Result.success(stats);
    }

    @GetMapping({"/rooms/mbti/{mbtiType}"})
    public Result<Map<String, Object>> getRoomsByMBTI(@PathVariable String mbtiType) {
        try {
            MBTISquare mbtiSquare = MBTISquare.fromString(mbtiType);
            if (mbtiSquare == null) {
                return Result.success(Map.of("message", "无效的MBTI类型: " + mbtiType));
            } else {
                List<RoomInfo> rooms = this.roomService.getRoomsByMBTISquare(mbtiSquare);
                List<Map<String, Object>> roomsWithPlayers = rooms.stream().map((room) -> Map.of("roomInfo", room, "players", this.roomService.getPlayersInRoom(room.getRoomId()))).toList();
                Map<String, Object> response = Map.of("mbtiSquare", mbtiSquare, "rooms", roomsWithPlayers, "totalRooms", rooms.size(), "totalPlayers", rooms.stream().mapToInt(RoomInfo::getCurrentPlayers).sum(), "activeRooms", rooms.stream().filter((room) -> room.getCurrentPlayers() > 0).count());
                return Result.success(response);
            }
        } catch (Exception e) {
            log.error("根据MBTI获取房间信息时出现异常: {}", e.getMessage(), e);
            return Result.success(Map.of("message", "获取房间信息失败: " + e.getMessage()));
        }
    }

    @GetMapping({"/mbti/stats"})
    public Result<Map<String, Object>> getMBTIStats() {
        try {
            Map<MBTISquare, Integer> stats = this.roomService.getMBTISquareStats();
            Map<String, Object> response = new HashMap();
            Map<String, Map<String, Object>> mbtiStats = new HashMap();

            for(Map.Entry<MBTISquare, Integer> entry : stats.entrySet()) {
                MBTISquare mbti = (MBTISquare)entry.getKey();
                Map<String, Object> mbtiInfo = Map.of("type", mbti.name(), "displayName", mbti.getDisplayName(), "description", mbti.getDescription(), "roomCount", entry.getValue());
                mbtiStats.put(mbti.name(), mbtiInfo);
            }

            response.put("mbtiStats", mbtiStats);
            response.put("totalTypes", MBTISquare.values().length);
            return Result.success(response);
        } catch (Exception e) {
            log.error("获取MBTI统计信息时出现异常: {}", e.getMessage(), e);
            return Result.success(Map.of("message", "获取统计信息失败: " + e.getMessage()));
        }
    }

    @GetMapping({"/mbti/types"})
    public Result<Map<String, Object>> getMBTITypes() {
        try {
            Map<String, Map<String, Object>> types = new HashMap();

            for(MBTISquare mbti : MBTISquare.values()) {
                Map<String, Object> typeInfo = Map.of("type", mbti.name(), "displayName", mbti.getDisplayName(), "description", mbti.getDescription());
                types.put(mbti.name(), typeInfo);
            }

            Map<String, Object> response = Map.of("types", types, "totalCount", MBTISquare.values().length);
            return Result.success(response);
        } catch (Exception e) {
            log.error("获取MBTI类型列表时出现异常: {}", e.getMessage(), e);
            return Result.success(Map.of("message", "获取类型列表失败: " + e.getMessage()));
        }
    }
}
